<?php
if(defined('CATALOG_PATH')) require_once(CATALOG_PATH.'model/leko/service.php');
else require_once(DIR_APPLICATION.'model/leko/service.php');

class ModelLekoOrderService extends ModelLekoService
{
    private $request, $products;

    private static $statusesNames=array(
        'New'=>1,
        'Processed'=>2,
        'Ready'=>3,
        'Ordered'=>3,
    );

    public function sendOrder($orderId,$orderData)
    {
        $model=$this->model->load('orderModel');
        $result=new stdClass();

        if($model->getTimeLimit($orderId)) return $result;

        if(!$oldInfo=$model->findByPk($orderId)){
            $this->error='Не удалось найти заказ';
            return false;
        }

        if(!$orderData){
            $orderProd=$this->model->load('orderProductModel');
            if(!$orderData=$orderProd->findAllByAttributes(array('order_id'=>$orderId))){
                $this->error='В заказе нет ни одного товара!';
                return false;
            }
        }

        $this->methodName='CreateOrder';

        if($params=$this->creteOrderInfo($orderData,$oldInfo)){
            $this->params=array('basketItems'=>$params);

            $soap=$this->getSoap();

            $result=$soap;

            if(!is_object($result) || $this->error){
                $result=new stdClass();
                $result->error=$this->error;
            }
            else $result->error='';
        }

        return $result;
    }

    public function updateOrder($id)
    {
        $orderModel=$this->model->load('orderModel');
        $limit=$orderModel->getTimeLimit($id);

        if($limit && time()-$limit<=$this->config->get('config_order_update_limit')) return false;
        $orderStatus=$orderModel->getStatus($id,'order_status_id');
        if($orderStatus!=2) return false;

        $result=false;

        $this->methodName='GetEntries';
        $this->params=array(
            'uid'=>'',
            'statuses'=>array(1,2,3,4,5,6,7),
        );
        $this->request=array('GetEntriesResult','CustomerEntryModel');

        if($orderProducts=$orderModel->getOrderProducts($id)){
            $model=$this->model->load('orderProductModel');
            $deleted=$model->deleteByAttributes(array('order_id'=>$id));

            $orderUids=array();
            $newProducts=array();

            foreach($orderProducts as $prod){
                if(!in_array($prod['Entry_UID'],$orderUids)){
                    $orderUids[]=$this->params['uid']=$prod['Entry_UID'];

                    if($products=$this->getSoap()){
                        if($newProduct=$this->updateOrderProducts($prod,$products,$model)){
                            $newProducts[]=$newProduct;
                        }else{
                            //unset($prod['order_product_id']);
                            if($deleted) $model->save($prod);
                        }
                    }
                }
            }

            $result=$orderModel->update($id,array('time_limit'=>time()));

            if($newProducts){
                $status=false;
                $firstProd=array_shift($newProducts);
                if(isset($firstStatus['status_id'])) $status=$firstProd['status_id'];

                if($newProducts){
                    foreach($newProducts as $prod){
                        if(isset($prod['status_id']) && $prod['status_id']!=$status){
                            $status=false;
                            break;
                        }
                    }
                }

                if($status && $status!=$orderStatus){
                    $result=$orderModel->update($id,array('order_status_id'=>$status));
                }
            }
        }

        return $result;
    }

    public function getUid($prodId,$orderId)
    {
        $uid='';
        for($i=0; $i<8-strlen($orderId); $i++){
            $uid.='0';
        }
        $uid.=$orderId.'-0000-0000-0000-';

        for($i=0; $i<12-strlen($prodId); $i++){
            $uid.='0';
        }
        return $uid.$prodId;
    }

    private function creteOrderInfo($newInfo,$oldInfo)
    {
        $this->orderNum=$oldInfo['order_id'];
        if(!$oldInfo || !$newInfo) return false;

        foreach($oldInfo as $name=>$value){
            if(isset($newInfo[$name]) && $newInfo[$name]!=$value) $oldInfo[$name]=$newInfo[$name];
        }

        $order=array();
        $prodModel=$this->model->load('productModel');


        foreach($newInfo as $product){
            $quantity=isset($product['quantity']) ? $product['quantity'] : 1;
            $productOld=$prodModel->findModelAttributesByPk($product['product_id'],array(
                'product_id',
                'ReplacementID',
                'product_wholesale_id',
                'warehouse',
                'WhQuantity',
                'SupplierRef',
                'price',
                'stock_status_id',
            ));

            $order[]=array(
                'Entry_UID'=>isset($product['Entry_UID']) ? $product['Entry_UID'] : 0,
                'StatusRef'=>isset($oldInfo['StatusRef']) ? $oldInfo['StatusRef'] : 0,
                'OrderRef'=>isset($oldInfo['OrderRef']) ? $oldInfo['OrderRef'] : 0,
                'ART_ID'=>isset($productOld['product_wholesale_id']) ? $productOld['product_wholesale_id'] : (isset($oldInfo['product_wholesale_id']) ? $oldInfo['product_wholesale_id'] : 0),
                'Quantity'=>$quantity,
                'Price'=>$productOld['price'],
                'Replacement_ID'=>$productOld['ReplacementID'] ? $productOld['ReplacementID'] : $productOld['product_wholesale_id'],
                'TypeWHOrigin'=>isset($productOld['stock_status_id']) ? $productOld['stock_status_id'] : (isset($oldInfo['TypeWHOrigin']) ? $oldInfo['TypeWHOrigin'] : 0),
                'SupplierRef'=>isset($productOld['SupplierRef']) ? $productOld['SupplierRef'] : (isset($oldInfo['SupplierRef']) ? $oldInfo['SupplierRef'] : 0),
                'PriceListRef'=>isset($productOld['PriceListRef']) ? $productOld['PriceListRef'] : (isset($oldInfo['PriceListRef']) ? $oldInfo['PriceListRef'] : 0),
                'OrderNumber'=>$product['order_id'],
                'Order_ID'=>$product['order_id'],
            );
        }

        return $order;
    }

    private function updateOrderProducts($product,$newProd,$model)
    {
        $result=false;
        $newProd=is_array($newProd) ? $newProd : array($newProd);

        $productsToUpdate=$newProd;

        if($productsToUpdate){
            foreach($productsToUpdate as $prod){
                if(!isset($prod->Id)) continue;

                $this->products[]=$prod;

                if(isset($product['status_id']) && isset($prod->StatusRef)){
                    if(array_key_exists($prod->StatusRef,self::$statusesNames)) $product['status_id']=self::$statusesNames[$prod->StatusRef];
                }
                $product['quantity']=$prod->Quantity;
                if(isset($product['total'])) $product['total']=$prod->Sum;
                if(isset($product['money'])){
                    $product['money']=$prod->Sum;
                    $product['money_left']=$prod->price*$prod->Quantity-$prod->Sum;
                }

                $product['wholesaleId']=$prod->Id;
                $product['wholesaleNumber']=$prod->Number;
                $product['wholesaleOrderId']=$prod->Order;

                unset($product['order_product_id']);
                if($model->save($product)) $result=$product;
            }
        }

        return $result;
    }

    private  function getSoap()
    {
        if(defined('CATALOG_PATH')) require_once(CATALOG_PATH.'model/leko/wsdl.php');
        else require_once(DIR_APPLICATION.'model/leko/wsdl.php');

        if(!$this->params) return false;

        $method=$this->methodName;
        $params=$this->params;

        $wsdl=new Wsdl(parent::WSDL_URL, $params, $this->request);
        $result=$wsdl->$method;

        $message=$this->error=$wsdl->errorMessage;
        if(isset($result->Error)) $message.='\r\n  '.$result->Error;
        if($message) $this->log->write($message);

        if(!$result){
            $this->error='Неудачное обращение к веб-службе';
        }elseif(isset($result->Error)){
            $this->error=$this->error ? '; '.$result->Error : $result->Error;
        }

        return $result;
    }
}